require([
	"jquery",
	"../js/xhr",
	"highcharts",
	"WdatePicker",
	"laydate"
], function($, xhr, highcharts, WdatePicker, laydate) {
	var host_url = "http://118.31.13.69:1001/";

	//每秒刷新时间
	setInterval(function() {
		fDate();
	}, 1000);

	//获取当前时间
	function fDate() {
		var dat = new Date();
		var year = dat.getFullYear();
		var month = dat.getMonth();
		var day = dat.getDate();
		var hours = dat.getHours();
		var minutes = dat.getMinutes();
		var seconds = dat.getSeconds();

		var time = year + "-" + fnW((month + 1)) + "-" + fnW(day) + "    " + fnW(hours) + ":" + fnW(minutes) + ":" + fnW(seconds);
		$("#p-date").text(time);

		return year + "-" + fnW((month + 1)) + "-" + fnW(day);
	}
	//补位 当某个字段不是两位数时补0
	function fnW(str) {
		var num;
		str > 9 ? num = str : num = "0" + str;
		return num;
	}

	/**       
	 * 时间戳转换日期       
	 * @param <int> unixTime  待时间戳(秒)       
	 * @param <bool> isFull  返回完整时间(Y-m-d 或者 Y-m-d H:i:s)       
	 * @param <int> timeZone  时区       
	 */
	function timeToDate(unixTime, isFull, timeZone) {
		if(typeof(timeZone) == 'number') {
			unixTime = parseInt(unixTime) + parseInt(timeZone) * 60 * 60;
		}
		var time = new Date(unixTime * 1000);
		var ymdhis = "";
		ymdhis += time.getUTCFullYear() + "-";
		ymdhis += (time.getUTCMonth() + 1) + "-";
		ymdhis += time.getUTCDate();
		if(isFull === true) {
			ymdhis += " " + time.getUTCHours() + ":";
			ymdhis += time.getUTCMinutes() + ":";
			ymdhis += time.getUTCSeconds();
		}
		return ymdhis;
	}
	////////////////////////////////////////////

	//设置成功dialog
	function succDialog(dat, isSucc) {
		$("#dialog").html(dat);
		$("#dialog").show();
		if(isSucc) {
			$("#dialog").css("background-color", "#4CAF50");
		} else {
			$("#dialog").css("background-color", "red");
		}
		setTimeout('$("#dialog").hide();', 1500);
	}

	//显示加载dialog
	function loadingDialog(isShow) {
		if(isShow) {
			$(".img-loading").show();
		} else {
			$(".img-loading").hide();
		}
	}

	//连接状态显示
	function connectStatue(isOk, time) {
		if(isOk) {
			$("#connect-statue .statue").html("连接正常  " + time + "ms");
			$("#connect-statue .statue").css("color", "#4CAF50");

		} else {
			$("#connect-statue .statue").html("连接失败 -" + time + "  正在重连...");
			$("#connect-statue .statue").css("color", "red");
		}
	}

	//日期控件
	$("#demo").focus(function(e) {
		laydate({
			elem: '#demo'
		})
	})
	$("#demo1").focus(function(e) {
		laydate({
			elem: '#demo1'
		})
	})
	$("#demo2").focus(function(e) {
		laydate({
			elem: '#demo2'
		})
	})
	$("#demo3").focus(function(e) {
		laydate({
			elem: '#demo3'
		})
	})

	$("#start_time").focus(function(e) {
		laydate({
			elem: '#start_time'
		})
	})

	$("#end_time").focus(function(e) {
		laydate({
			elem: '#end_time'
		})
	})
	//
	$(".table #div-tb").click(function(e) {
		e.stopPropagation();
	})
	$(".table1 #excle").click(function(e) {
		e.stopPropagation();
	})
	////////////////////////////////////////////

	//初始化默认执行一次调用数据
	getPigs();

	//请求网络数据-获取所有的猪宝宝
	var datalist = null;
	$("#choose-pig").click(function() {
		if(!$(this).hasClass("choose-bg")) {
			if(datalist != null) return;
			console.log("获取所有的猪宝宝...");
			getPigs();
		}
	})

	//
	function getPigs() {
		loadingDialog(true);
		$.ajax({
				url: host_url + "api/v1/pig?pageSize=100",
				type: "get",
				headers: {
					"Content-Type": "application/json; charset=utf-8",
				},
				cache: false,
				contentType: "application/json",
				//				beforeSend: function(xhr) {
				//					xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); //配置跨域访问,需要后端支持
				//				}
			})
			.done(function(data, textStatus, jqXHR) {
				datalist = data._embedded.pigConfigs;
				$("#pig-list-data").html("");
				var html = "";
				if(datalist.length <= 0) {
					succDialog("无猪数据", false);
					return;
				}

				for(var i = 0; i < datalist.length; i++) {
					html += "<li class = 'two-li'  data-id=" + datalist[i].pid + ">" + datalist[i].pid + "</li>";
					console.log(datalist[i].doctorName);
				};
				$("#pig-list-data").html(html);
				//选择猪宝宝二级菜单 动态生成
				loadingDialog(false);
				chooseSingPig(datalist[0]);

			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				succDialog("获取数据失败" + errorThrown, false);

			})
			.always(function() {
				loadingDialog(false);
			});

		//		xhr.req({
		//			url: "http://98.142.130.160:1001/api/v1/pig?pageSize=100",
		//			type: "get",
		//			success: function(data) {
		//				datalist = data._embedded.pigConfigs;
		//				$("#pig-list-data").html("");
		//				var html = "";
		//				for(var i = 0; i < datalist.length; i++) {
		//					html += "<li class = 'two-li'  data-id=" + datalist[i]._links.pigConfig.href + ">" + datalist[i].pid + "</li>";
		//					console.log(datalist[i].doctorName);
		//				};
		//				$("#pig-list-data").html(html);
		//				//选择猪宝宝二级菜单 动态生成
		//				chooseSingPig(datalist[0]);
		//			},
		//			error: function(data) {
		//				console.log(data);
		//			},
		//			complete: function() {
		//				loadingDialog(false);
		//			}
		//		});
	}

	//点击导航栏条目 高亮样式  1-移除同级别条目的高亮样式   2- 当前点击的条目添加高亮
	$(".box-left-menu-ul>li").click(function() {
		if($(this).hasClass("choose-bg")) {
			$(this).removeClass("choose-bg");
		} else {
			$(this).addClass("choose-bg").siblings().removeClass("choose-bg");
		}
		$(this).addClass("box-li-backcolor").siblings().removeClass("box-li-backcolor");

	});

	$(".history").click(function() {
		$(".table").show();
		$(".table .Wdate").attr("value", fDate());
		var pid = $("#pig-name").attr("data-pid");
		$(".table .xyz").html("猪编号：" + pid + " - 姿态数据记录");
		$(".table #div-tb2 .zitai").html("猪编号：" + pid + " - 姿态全览");
	})
	$(".table").click(function() {
		$(".table").hide();
	})

	$(".output").click(function() {
		$(".table1").show();
		var pid = $("#pig-name").attr("data-pid");
		$("#pig_name").html("猪编号：" + pid);
	})

	$(".table1").click(function() {
		$(".table1").hide();
	})

	//搜索历史记录
	$("#search").click(function() {
		page = 0;
		getPigDateInfo();

	})

	$("#input_daochu").click(function() {

		//TODO 导出excle
		var value2 = $("#demo2").val();
		var value3 = $("#demo3").val();
		daoChuExcle(value2, value3);
	})

	//上一页
	$(".l-page").click(function() {
		//TODO 上一页

		if(page <= 0) {
			succDialog("已经是第一页了", false);
			return;
		}
		page--;
		getPigDateInfo();
	})

	//下一页
	var isLast = false;
	$(".r-page").click(function() {
		//TODO 下一页

		if(isLast) {
			succDialog("已经是最后一页了", false);
			return;
		}
		page++;
		getPigDateInfo();
	})

	//导出
	$("#daoc").click(function() {
		//TODO 导出
		//		var url = "http://98.142.130.160:1001/api/v1/pigDatas/search/findByPigIdAndTimeBetton?pig="+pid+"&t1="+startTime+"&t2="+endTime;
		//		location.href = host_url + "excel/pigDatas?.xls";
		//		window.open("http://740b2e83.ngrok.io/excel/pigDatas.xls");
		var value = $("#demo").val();
		var value1 = $("#demo1").val();
		daoChuExcle(value, value1);
	})

	function daoChuExcle(value, value1) {

		//		var value = $("#demo2").val();
		var timestamp = Date.parse(new Date(value)) / 1000;

		//		var value1 = $("#demo3").val();
		var timestamp1 = Date.parse(new Date(value1)) / 1000;

		if(value == "" || value1 == "") {
			succDialog("日期格式不正确", false);
			return;
		}

		console.log("value1 - value" + getDays(value, value1));
		if(getDays(value, value1) > 31) {
			succDialog("不能超过31天", false);
			return;
		}

		if(timestamp1 - timestamp < 0) {
			succDialog("起始时间必须小于结束时间", false);
			return;
		}

		var downurl = host_url + "excel/pigDatas.zip?t1=" + timestamp + "&t2=" + timestamp1 + "&pid=" + $("#pig-name").attr("data-pid");
		//		window.open(downurl);
		location.href = downurl;
		//		location.href = "http://118.31.13.69:1001/excel/pigDatas.zip";
	}

	//根据日期查询猪的数据
	var page = 0;

	function getPigDateInfo() {
		var value = $("#demo").val();
		var timestamp = Date.parse(new Date(value)) / 1000;

		var value1 = $("#demo1").val();
		var timestamp1 = Date.parse(new Date(value1)) / 1000;

		if(value == "" || value1 == "") {
			succDialog("日期格式不正确", false);
			return;
		}

		console.log("value1 - value" + getDays(value, value1));
		if(getDays(value, value1) > 31) {
			succDialog("不能超过31天", false);
			return;
		}

		if(timestamp1 - timestamp < 0) {
			succDialog("起始时间必须小于结束时间", false);
			return;
		}

		var pid = $("#pig-name").attr("data-pid");
		loadingDialog(true);
		$.ajax({
				url: host_url + "api/v1.1/pigDatas/history?pid=" + pid + "&t1=" + timestamp + "&t2=" + timestamp1 + "&page=" + page + "&pageSize = 20",
				type: "get",
				headers: {
					"Content-Type": "application/json; charset=utf-8",
				},
				cache: false,
				contentType: "application/json",
				//				beforeSend: function(xhr) {
				//					xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); //配置跨域访问,需要后端支持
				//				}
			})

			.done(function(data, textStatus, jqXHR) {
				//TODO 获取到数据之后开始加载表格
				loadingTable1Data(data.data.data);
				loadingTable2Data(data.count);

				$(".c-page").html("第" + (page + 1) + "页,共" + data.data.totalPage + "页");
				if(data.data.totalPage == page + 1) {
					isLast = true;
				} else {
					isLast = false;
				}
			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				succDialog("获取数据失败" + errorThrown, false);

			})
			.always(function() {
				loadingDialog(false);
			});
	}

	//查询两个日期之间的相差的天数
	function getDays(strDateStart, strDateEnd) {
		var strSeparator = "-"; //日期分隔符
		var oDate1;
		var oDate2;
		var iDays;
		oDate1 = strDateStart.split(strSeparator);
		oDate2 = strDateEnd.split(strSeparator);
		var strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
		var strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
		iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数 
		return iDays;
	}

	//选择猪宝宝二级菜单
	var currentPigUrl = "";

	function chooseSingPig(dat) {
		//轮训刷传感器相关数据 3秒
		currentPigUrl = dat.pid;
		setInterval(function() {
			//			alert(currentPigUrl);
			getSinglePigInfo(currentPigUrl);
		}, 3000);

		setInterval(function() {
			setChar(currentPigUrl);
		}, 5 * 1000 * 60); //5分钟获取一下图表

		$("#pig-name").html("当前猪宝宝：" + dat.pid);
		$("#pig-name").attr("data-pid", dat.pid);
		$("#set-time").html(dat.st + " 分钟");
		$("#pig-list-data .two-li").click(function(e) {
			e.stopPropagation();
			$(this).addClass("two-li-choose").siblings().removeClass("two-li-choose");
			currentPigUrl = $(this).attr("data-id");
			$(".img-loading").show();
			getSinglePigInfo(currentPigUrl);
		});

		setChar(currentPigUrl);

	}

	//请求单个猪的信息 根据
	var isNetBack = true;

	function getSinglePigInfo(_url) {
		if(!isNetBack) {
			return;
		}
		isNetBack = false;
		var timestamp = (new Date()).valueOf();
		xhr.req({
			url: host_url + "api/v1/pigDatas/search/findByPigId?" + "pigId=" + _url + "&size=1&sort=id,desc",
			type: "get",
			cache: false,
			success: function(data) {
				console.log(data);
				$("#pig-name").html("当前猪宝宝：" + _url);
				$("#pig-name").attr("data-pid", _url);

				var times = (new Date()).valueOf() - timestamp;
				connectStatue(true, times)

				var pigData = data._embedded.pigDatas;
				if(pigData.length > 0) {
					var _ax = pigData[0].ax;
					var _ay = pigData[0].ay;
					var _az = pigData[0].az;
					var _wx = pigData[0].wx;
					var _wy = pigData[0].wy;
					var _wz = pigData[0].wz;
					var _posture = pigData[0].posture;

					$("#div-data-w .p-xw").html("X角度：" + _wx);
					$("#div-data-w .p-yw").html("Y角度：" + _wy);
					$("#div-data-w .p-zw").html("Z角度：" + _wz);

					$("#div-data-a .p-xa").html("X加速度：" + _ax);
					$("#div-data-a .p-ya").html("Y加速度：" + _ay);
					$("#div-data-a .p-za").html("Z加速度：" + _az);

					$(".div-p .p-statue").html("当前姿态：" + changeStuta(_posture));

				}
			},
			error: function(data) {
				console.log(data);
				connectStatue(false, data.status);
			},
			complete: function() {
				loadingDialog(false);
				isNetBack = true;
			}
		});
	}

	function changeStuta(_posture) {
		var _postureStatue = "";
		switch(_posture) {
			case 1:
				_postureStatue = "运动";
				break;
			case 2:
				_postureStatue = "站（静止）";
				break;
			case 3:
				_postureStatue = "趴（静止）";
				break;
			case 4:
				_postureStatue = "躺（静止）";
				break;
			default:
				_postureStatue = "未知";
				break;
		}

		return _postureStatue;
	}

	//选择采样时间二级菜单
	$("#pig-list-time .two-li").click(function(e) {
		e.stopPropagation();
		$(this).addClass("two-li-choose").siblings().removeClass("two-li-choose");
		var _id = $(this).attr("data-id");
		var _pid = $("#pig-name").attr("data-pid");
		//		var data = {
		//			"pid": _pid,
		//			"st": _id
		//		};
		$.ajax({
				url: host_url + "api/v1/pig/1",
				type: "PUT",
				headers: {
					"Content-Type": "application/json; charset=utf-8",
				},
				contentType: "application/json",
				beforeSend: function(xhr) {
					xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); //配置跨域访问,需要后端支持
				},
				data: JSON.stringify({
					"pid": _pid,
					"st": _id
				})
			})
			.done(function(data, textStatus, jqXHR) {
				console.log("HTTP Request Succeeded: " + jqXHR.status);
				console.log(data);
				$("#set-time").html(data.st + " 分钟");
				succDialog("设置成功", true);
			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				console.log("HTTP Request Failed");
				succDialog("设置失败" + errorThrown, false);

			})
			.always(function() {
				/* ... */
			});
		//				xhr.req({
		//					url: "http://98.142.130.160:1001/api/v1/pig/1",
		//					type: "PUT",
		//					data: JSON.stringify({"pid": _pid,"st": _id}),
		////					data: data,
		//					success: function(data) {
		//						console.log(data);
		//					},
		//					error: function(data) {
		//						console.log(data);
		//					},
		//					complete: function() {}
		//				});
	});

	/////////////////////////////////////////////////////

	//图表
	var chart = {
		type: 'column'
	};
	var title = {
		text: "猪宝宝-当日姿态统计图"
	};
	var subtitle = {
		//		text: "."
		text: fDate()
	};
	var xAxis = {
		categories: ['站(静止)', '趴(静止)', '躺(静止)', '运动'],
		crosshair: true,
	};
	var yAxis = {
		min: 0,
		title: {
			text: '时长：小时'
		}
	};
	var tooltip = {
		headerFormat: '<span style="font-size:10px,text-align:center" >{point.key}</span><table>',
		pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
			//			'<td style="padding:0"><b>{point.y:.1f} 小时</b></td></tr>',
			'<td style="padding:0"><b>{point.y:.1f} 小时</b></td></tr>',
		footerFormat: '</table>',
		shared: true,
		useHTML: true
	};
	var plotOptions = {
		column: {
			pointPadding: 0.2,
			borderWidth: 0
		}
	};
	var credits = {
		enabled: false
	};

	var series = [{
		name: '姿态',
		data: [0, 0, 0, 0, 0]
		// , {
		//          name: 'New York',
		//          data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]
		//      }, {
		//          name: 'London',
		//          data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]
		//      }, {
		//          name: 'Berlin',
		//          data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
		// }
	}];

	var json = {};
	json.chart = chart;
	json.title = title;
	json.subtitle = subtitle;
	json.tooltip = tooltip;
	json.xAxis = xAxis;
	json.yAxis = yAxis;
	json.series = series;
	json.plotOptions = plotOptions;
	json.credits = credits;
	$('#chart1').highcharts(json);

	/**
	 * 设置图表
	 */
	function setChar(pid) {
		var series;
		$.ajax({
				url: host_url + "api/v1.1/pigDatas/count?pig=" + pid + searchTimeUrl,
				type: "get",
				headers: {
					"Content-Type": "application/json; charset=utf-8",
				},
				cache: false,
				contentType: "application/json",
				//				beforeSend: function(xhr) {
				//					xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); //配置跨域访问,需要后端支持
				//				}
			})
			.done(function(data, textStatus, jqXHR) {
				series = [{
					name: '姿态',
					data: data.data
				}];
				var json = {};
				json.chart = chart;
				json.title = title;
				json.subtitle = subtitle;
				json.tooltip = tooltip;
				json.xAxis = xAxis;
				json.yAxis = yAxis;
				json.series = series;
				json.plotOptions = plotOptions;
				json.credits = credits;
				$('#chart1').highcharts(json);

			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				succDialog("图表获取数据失败" + errorThrown, false);

			})
			.always(function() {});

	}

	//	setInterval(function(){
	//		test();
	//	},2000);
	//
	//	function test() {
	//		alert(1);
	//		series = [{
	//			name: '姿态',
	//			data: [5, 6, 9, 8, 74, 95, 5]
	//		}];
	//		var json = {};
	//		json.chart = chart;
	//		json.title = title;
	//		json.subtitle = subtitle;
	//		json.tooltip = tooltip;
	//		json.xAxis = xAxis;
	//		json.yAxis = yAxis;
	//		json.series = series;
	//		json.plotOptions = plotOptions;
	//		json.credits = credits;
	//		$('#chart1').highcharts(json);
	//
	//	}

	////////////////////////////////////////////////////////
	/////表格
	//	loadingTable1Data(formData);
	//	loadingTable2Data(formData);

	//加载 表格1数据
	var thHtml = "";

	function loadingTable1Data(formData) {
		$("#tbody").html("");
		thHtml = "";
		for(var i = 0; i < formData.length; i++) {
			var form = formData[i]
			thHtml += "<tr>";
			thHtml += "<td>" + (i + 1) + "</td>";
			thHtml += "<td>" + form.time + "</td>";
			thHtml += "<td>" + form.pigId + "</td>";
			thHtml += "<td>" + changeStuta(form.posture) + "</td>";
			thHtml += "</tr>";
			$("#tbody").html(thHtml);
		}
	}

	//加载 表格2数据
	var tb2Html = "";

	function loadingTable2Data(formData) {
		$("#tbody2").html("")
		tb2Html = "";
		for(var i = 0; i < formData.length; i++) {
			var form = formData[i];
			tb2Html += "<tr>";
			tb2Html += "<td>" + form.day + "</td>";
			tb2Html += "<td>" + hourToMin(form.posture_2) + "</td>";
			tb2Html += "<td>" + hourToMin(form.posture_3) + "</td>";
			tb2Html += "<td>" + hourToMin(form.posture_4) + "</td>";
			tb2Html += "<td>" + hourToMin(form.posture_1) + "</td>";
			tb2Html += "</tr>";
			$("#tbody2").html(tb2Html);
		}
	}

	function hourToMin(hour) {
		var hh = Math.floor(hour);
		var mm = (hour - hh) * 60;
		var m1 = Math.floor(mm);

		return hh + "小时" + m1 + "分钟";
	}

	var searchTimeUrl = "";

	//选择时间转换
	$("#btn_time").click(function() {
		$("#btn_time").hide();
		$("#btn_doday").hide();
		$("#chart1-ctime").show();
	})

	$("#btn_sure").click(function() {
		//开始查询
		var value = $("#start_time").val();
		var timestamp = Date.parse(new Date(value)) / 1000;

		var value1 = $("#end_time").val();
		var timestamp1 = Date.parse(new Date(value1)) / 1000;

		if(value == "" || value1 == "") {
			succDialog("日期格式不正确", false);
			return;
		}

		console.log("value1 - value" + getDays(value, value1));
		if(getDays(value, value1) > 31) {
			succDialog("不能超过31天", false);
			return;
		}

		if(timestamp1 - timestamp < 0) {
			succDialog("起始时间必须小于结束时间", false);
			return;
		}

		$("#btn_time").hide();
		$("#btn_doday").show();
		$("#chart1-ctime").hide();
		loadingDialog(true);
		searchTimeUrl = "&t1=" + timestamp + "&t2=" + timestamp1;
		title = {
			text: "猪编号："+currentPigUrl+","+value+"~"+value1+"姿态统计图"
		}
		subtitle = {
			text: value + "~" + value1
		};
		setChar(currentPigUrl);
	})

	$("#btn_cancle").click(function() {
		$("#btn_time").show();
		$("#btn_doday").hide();
		$("#chart1-ctime").hide();
	})

	$("#btn_doday").click(function() {
		$("#btn_time").show();
		$("#btn_doday").hide();
		$("#chart1-ctime").hide();
		loadingDialog(true);
		searchTimeUrl = "";
		title = {
			text: '猪编号：'+currentPigUrl+",当日姿态统计图"
		}
		subtitle = {
			text: fDate()
		};
		setChar(currentPigUrl);
	})

})